package com.dj.web.login.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.dj.core.user.LoginService;
import com.dj.core.user.api.UserNamePasswordErrorException;
import com.dj.domain.entity.DaiJiaUser;
import com.dj.web.utils.DaijiaWebUserUtil;

/**
 * 登录
 * 
 * @author jasen.hsu.cn@gmail.com 2012-4-17 下午1:33:23
 */
@Controller
public class LoginController {

    private static final String DONE = "done";

    @Autowired
    private LoginService        loginService;

    /**
     * 登录
     * 
     * @param request
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/login")
    public String login(Model model, HttpServletRequest request) {
        String toUrl = request.getParameter(DONE);
        boolean isUrlValid = this.isUrlValid(toUrl);
        // TODO:重定向
        /** 已登录 */
        if (DaijiaWebUserUtil.isLogon(request)) {
            if (isUrlValid) {
                return "redirect:" + toUrl;
            }
            return "/login/login_success";
        }
        LoginForm loginForm = new LoginForm();
        if (isUrlValid) {
            loginForm.setToUrl(toUrl);
        }
        /** 未登录 */
        model.addAttribute(loginForm);
        return "/login/login_index";
    }

    /**
     * 登录
     * 
     * @param request
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/logout")
    public String logout(HttpServletRequest request) {
        DaijiaWebUserUtil.removeUserToSession(request);
        return "/index";
    }

    /**
     * 登录
     * 
     * @param request
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/login")
    public String loginFromDaijia(@Valid LoginForm loginForm, BindingResult result, HttpServletRequest request) {
        if (result.hasErrors()) {
            return "/login/login_index";
        }

        String toUrl = loginForm.getToUrl();
        boolean isUrlValid = this.isUrlValid(toUrl);

        // 登录是否成功
        try {
            this.login(loginForm, request);
            if (isUrlValid) {
                return "redirect:" + toUrl;
            }
            return "/login/login_success";
        } catch (UserNamePasswordErrorException e) {
            FieldError error = new FieldError("loginForm", "password", "您输入的用户名或密码不正确。");
            result.addError(error);
            return "/login/login_index";
        }
        // TODO:重定向
    }

    @RequestMapping(value = "/test/user")
    public ModelAndView getUser(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView result = new ModelAndView();
        result.addObject("_data_", DaijiaWebUserUtil.getUserFromRequest(request));
        return result;
    }

    private void login(LoginForm user, HttpServletRequest request) throws UserNamePasswordErrorException {
        if (user != null && StringUtils.hasLength(user.getLoginId()) && StringUtils.hasLength(user.getPassword())) {
            DaiJiaUser loginUser = loginService.loginIn(user.getLoginId().toLowerCase(), user.getPassword());
            DaijiaWebUserUtil.storeUserToSession(loginUser, request);
        }
    }

    private boolean isUrlValid(String url) {
        if (StringUtils.hasLength(url) && !url.contains("login")) {// && url.startsWith("http://www.daijia.com")) {
            return true;
        }
        return false;
    }
}
